import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:leader_doctor_flutter/common/widget/comm_widget.dart';
import 'package:leader_doctor_flutter/styles/colors.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';

/// @Author lixiaobin
/// @Date 2024/2/29
/// @Description 图片画廊
class ImageGalleryPage extends StatefulWidget {
  final List<String> galleryItems;
  final int? selectIndex;

  const ImageGalleryPage(
      {super.key, required this.galleryItems, this.selectIndex = 0});

  @override
  State<ImageGalleryPage> createState() => _ImageGalleryPageState();
}

class _ImageGalleryPageState extends State<ImageGalleryPage> {
  PageController? _pageController;
  var _index = 0;

  @override
  void initState() {
    super.initState();
    _pageController = PageController(initialPage: widget.selectIndex ?? 0);
    _index = widget.selectIndex ?? 0;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: CommWidget.getCommAppbar(context),
        body: Stack(alignment: AlignmentDirectional.center, children: [
          _buildPhotoViewGallery(),
          Positioned(
              bottom: 20.w,
              child: Text(
                '${_index + 1}/${widget.galleryItems.length}',
                style: TextStyle(fontSize: 16.sp),
              ))
        ]));
  }

  Widget _buildPhotoViewGallery() {
    return PhotoViewGallery.builder(
      scrollPhysics: const BouncingScrollPhysics(),
      builder: (BuildContext context, int index) {
        var url = widget.galleryItems[index].toString();
        ImageProvider imageProvider;
        if (url.startsWith('http')) {
          imageProvider = NetworkImage(url);
        } else {
          imageProvider = AssetImage('assets/images/$url');
        }
        return PhotoViewGalleryPageOptions(
          imageProvider: imageProvider,
          initialScale: PhotoViewComputedScale.contained,
          minScale: PhotoViewComputedScale.contained * (0.5 + index / 10),
          maxScale: PhotoViewComputedScale.covered * 4.1,
          heroAttributes:
              PhotoViewHeroAttributes(tag: widget.galleryItems[index]),
        );
      },
      itemCount: widget.galleryItems.length,
      loadingBuilder: (context, event) => Center(
        child: SizedBox(
          width: 20.0,
          height: 20.0,
          child: CircularProgressIndicator(
            value: event == null
                ? 0
                : event.cumulativeBytesLoaded / (event.expectedTotalBytes ?? 0),
          ),
        ),
      ),
      backgroundDecoration: const BoxDecoration(color: ColorRes.white),
      pageController: _pageController,
      onPageChanged: (index) {
        _index = index;
        setState(() {});
      },
    );
  }
}
